<template>
	<el-dialog :title="form.id ? '编辑' : '新增'" width="70vw" v-model="visible" :close-on-click-modal="false" draggable>
		<el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="180px" v-loading="loading">
			<el-row :gutter="24">
				<el-col :span="12" class="mb20">
					<el-form-item label="项目名称" prop="projectName">
						<el-input v-model="form.projectName" placeholder="请输入项目名称" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="项目缩写" prop="projectAbbr">
						<el-input :disabled="form.id ? true : false" v-model="form.projectAbbr" placeholder="请输入项目缩写" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="省份" prop="province">
						<el-select
							filterable
							v-model="form.province"
							:disabled="form.projectApprovalStatus == 'approval'"
							placeholder="请选择省份"
							@change="form.area = ''"
						>
							<el-option v-for="item in provinceAndCityData" :key="item.value" :value="item.label" :label="item.label" />
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="地区" prop="area">
						<el-select v-model="form.area" :disabled="form.projectApprovalStatus == 'approval'" placeholder="请选择地区">
							<el-option v-for="item in cityData" :key="item.value" :value="item.label" :label="item.label" />
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="项目类型" prop="projectType">
						<el-select v-model="form.projectType" :disabled="form.projectApprovalStatus == 'approval'" placeholder="请选择项目类型">
							<el-option v-for="item in project_type" :key="item.id" :label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
				</el-col>

				<!--				        <el-col :span="12" class="mb20">
          <el-form-item label="项目年份" prop="projectYear">
            <el-date-picker v-model="form.projectYear" type="year" placeholder="请选择项目年份" value-format="YYYY" />
          </el-form-item>
        </el-col>-->
				<el-col :span="12" class="mb20">
					<el-form-item label="部门选择" prop="deptId">
						<el-tree-select
							:data="deptData"
							:props="{ value: 'id', label: 'name', children: 'children' }"
							check-strictly
							:render-after-expand="true"
							class="w100"
							clearable
							placeholder="请选择所属部门"
							v-model="form.deptId"
						>
						</el-tree-select>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="项目立项日期" prop="projectApprovalDate">
						<el-date-picker
							:disabled="form.projectApprovalStatus == 'approval'"
							v-model="form.projectApprovalDate"
							placeholder="项目立项日期"
							value-format="YYYY-MM-DD"
						/>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="项目签订日期" prop="projectSigningDate">
						<el-date-picker v-model="form.projectSigningDate" value-format="YYYY-MM-DD" placeholder="项目签订日期" />
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item label="项目计划开始日期" prop="planStartDate">
						<el-date-picker v-model="form.planStartDate" value-format="YYYY-MM-DD" placeholder="项目计划开始日期" />
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item label="项目计划结束日期" prop="planEndDate">
						<el-date-picker v-model="form.planEndDate" value-format="YYYY-MM-DD" placeholder="项目计划结束日期" />
					</el-form-item>
				</el-col>

				<el-col :span="24" class="mb20">
					<el-form-item label="项目内容" prop="projectContent">
						<Editor v-model:getHtml="form.projectContent" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="我方项目负责人" prop="projectMyHead">
						<UserSelect placeholder="我方项目负责人" v-model="form.projectMyHead" />
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item label="我方项目技术负责人" prop="projectMyTechnologyHead">
						<UserSelect placeholder="我方项目技术负责人" v-model="form.projectMyTechnologyHead" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="我方营销负责人" prop="projectMyMarketHead">
						<UserSelect placeholder="我方营销负责人" v-model="form.projectMyMarketHead" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="我方商务负责人" prop="projectMyBusinessHead">
						<UserSelect placeholder="我方商务负责人" v-model="form.projectMyBusinessHead" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="甲方单位" prop="partAUnit">
						<el-input v-model="form.partAUnit" placeholder="请输入甲方单位" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="过手单位" prop="passingUnit">
						<el-input v-model="form.passingUnit" placeholder="请输入过手单位" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="甲方负责人姓名" prop="partAPersonName">
						<el-input v-model="form.partAPersonName" placeholder="请输入甲方负责人姓名" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="甲方负责人联系方式" prop="partAPersonPhone">
						<el-input v-model="form.partAPersonPhone" placeholder="请输入甲方负责人联系方式" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="前期定价" prop="prePricing">
						<el-input v-model="form.prePricing" placeholder="请输入前期定价（元）" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="招投标" prop="tenderAndBid">
						<el-select v-model="form.tenderAndBid" placeholder="请选择招投标状态">
							<el-option v-for="item in tender_bid_status" :key="item.id" :label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20" v-if="form.tenderAndBid == 'complete'">
					<el-form-item label="中标通知" prop="noticeOfAward">
						<el-input v-model="form.noticeOfAward" placeholder="请输入中标通知" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="商务备注" prop="businessRemark">
						<el-input type="textarea" v-model="form.businessRemark" placeholder="请输入商务备注" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="中标服务费" prop="bidServiceFee">
						<el-input v-model="form.bidServiceFee" placeholder="请输入中标服务费（元）" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="中标服务费发票领取情况" prop="bidServiceFeeInvoice">
						<el-select v-model="form.bidServiceFeeInvoice" placeholder="请选择发票领取情况">
							<el-option v-for="item in fee_invoice" :key="item.id" :label="item.label" :value="item.value" :default-value="fee_invoice[0].value" />
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :span="24" class="mb20">
					<el-form-item label="附件" prop="fileList">
						<UploadV2 v-model="form.fileList" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">取消</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="ProjectBasicInfoDialog">
import { useDict } from '@/hooks/dict';
import { useMessage } from '@/hooks/message';
import { getObj, addObj, putObj } from '@/api/oa/projectBasicInfo';
import { provinceAndCityData } from '@/utils/chinaArea';
import UploadV2 from '@/components/UploadV2/index.vue';
import { useSelectOptionsStore } from '@/stores/selectOptions';
import UserSelect from '@/components/UserSelect/index.vue';
import { deptTree } from '@/api/admin/dept';

const store = useSelectOptionsStore();
store.fetchUserOptions(); // 请求用户数据

const cityData = computed(() => {
	return provinceAndCityData.find((item: any) => item.label === form.value.province)?.children || [];
});

const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
const deptData = ref<any[]>([]);

// 定义字典
const { project_type, fee_invoice, tender_bid_status } = useDict(
	'project_type',
	'project_status',
	'payment_collection_status',
	'fee_invoice',
	'tender_bid_status',
	'contract_sign'
);

function generateForm() {
	return {
		id: '',
		projectNumber: '',
		projectName: '',
		projectAbbr: '',
		projectType: null,
		province: '',
		area: '',
		projectContent: '',
		projectApprovalDate: '',
		projectSigningDate: '',
		planStartDate: '',
		planEndDate: '',
		contractAttributes: '',
		contractNumber: '',
		circulationTime: '',
		contractName: '',
		projectStatus: '',
		projectApprovalStatus: '',
		projectSchedule: '',
		projectMyHead: '',
		projectMyTechnologyHead: '',
		projectMyMarketHead: '',
		projectMyBusinessHead: '',
		partAUnit: '',
		passingUnit: '',
		partAPersonName: '',
		partAPersonPhone: '',
		prePricing: '',
		tenderAndBid: '',
		noticeOfAward: '',
		contractSign: '',
		projectYear: '',
		actualMoneyCurrentYear: '',
		expenditure: '',
		agencyFee: '',
		contractAmountYear: '',
		contractAmountTotal: '',
		contractSettlementAmount: '',
		invoiceAmountYear: '',
		receivedAmount: '',
		receivableAmount: '',
		dueInAmount: '',
		uncollected: '',
		expectedReturnTime: '',
		needReturnMoneyYear: '',
		realReturnMoneyYear: '',
		remainderMoneyYear: '',
		paymentCollectionYearStaus: '',
		businessRemark: '',
		bidServiceFee: '',
		bidServiceFeeInvoice: '',
		remark: '',
		fileList: [],
		userList: [],
	};
}

// 初始化部门数据
const getDeptData = () => {
	// 获取部门数据
	deptTree().then((res) => {
		deptData.value = res.data;
	});
};

// 提交表单数据
const form = ref(generateForm());

// 项目计划开始日期、项目计划结束日期校验规则
// 如果两个都有值，结束日期不能早于开始日期
const planStartDateValidator = (_: any, value: string, callback: Function) => {
	if (!value || !form.value.planEndDate) {
		callback();
	} else if (value >= form.value.planEndDate) {
		callback(new Error('开始日期不能晚于结束日期'));
	} else {
		callback();
	}
};
const planEndDateValidator = (_: any, value: string, callback: Function) => {
	if (!value || !form.value.planStartDate) {
		callback();
	} else if (value <= form.value.planStartDate) {
		callback(new Error('结束日期不能早于开始日期'));
	} else {
		callback();
	}
};

// 定义校验规则
const dataRules = ref({
	projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
	projectAbbr: [{ required: true, message: '项目缩写不能为空', trigger: 'blur' }],
	province: [{ required: true, message: '省份不能为空', trigger: 'blur' }],
	planStartDate: [{ validator: planStartDateValidator, trigger: 'blur' }],
	planEndDate: [{ validator: planEndDateValidator, trigger: 'blur' }],
	// area: [{required: true, message: '地区不能为空', trigger: 'blur'}],
	// projectContent: [{required: true, message: '项目内容不能为空', trigger: 'blur'}],
	// contractAttributes: [{required: true, message: '合同属性不能为空', trigger: 'blur'}],
	projectType: [{ required: true, message: '项目类型不能为空', trigger: 'blur' }],
	projectStatus: [{ required: true, message: '项目状态不能为空', trigger: 'blur' }],
	// projectSchedule: [{ required: true, message: '项目进度不能为空', trigger: 'blur' }],
	// projectMyHead: [{required: true, message: '我方项目负责人不能为空', trigger: 'blur'}],
	// projectMyTechnologyHead: [{required: true, message: '我方项目技术负责人不能为空', trigger: 'blur'}],
	// projectMyMarketHead: [{required: true, message: '我方营销负责人不能为空', trigger: 'blur'}],
	// projectMyBusinessHead: [{required: true, message: '我方商务负责人不能为空', trigger: 'blur'}],
	// partAUnit: [{required: true, message: '甲方单位不能为空', trigger: 'blur'}],
	// passingUnit: [{required: true, message: '过手单位不能为空', trigger: 'blur'}],
	// partAPersonName: [{required: true, message: '甲方负责人姓名不能为空', trigger: 'blur'}],
	// partAPersonPhone: [{required: true, message: '甲方负责人联系方式不能为空', trigger: 'blur'}],
	// prePricing: [{required: true, message: '前期定价(单位:元)不能为空', trigger: 'blur'}],
	// projectYear: [{required: true, message: '项目年份不能为空', trigger: 'blur'}],
	// actualMoneyCurrentYear: [{required: true, message: '当年实际合同金额(单位:元)不能为空', trigger: 'blur'}],
	// expenditure: [{required: true, message: '支出(单位:元)不能为空', trigger: 'blur'}],
	// agencyFee: [{required: true, message: '居间费(单位:元)不能为空', trigger: 'blur'}],
	// contractAmountYear: [{required: true, message: '年合同额(单位:元)不能为空', trigger: 'blur'}],
	// contractAmountTotal: [{required: true, message: '合同总额(单位:元)不能为空', trigger: 'blur'}],
	// contractSettlementAmount: [{required: true, message: '审定（结算）金额(单位:元)不能为空', trigger: 'blur'}],
	// invoiceAmountYear: [{required: true, message: '当年开票金额不能为空', trigger: 'blur'}],
	// receivedAmount: [{required: true, message: '已收账款[实际开票并到账金额]不能为空', trigger: 'blur'}],
	// receivableAmount: [{required: true, message: '应收账款[开票未到账金额]不能为空', trigger: 'blur'}],
	// dueInAmount: [{required: true, message: '待收账款[未开票金额]不能为空', trigger: 'blur'}],
	// uncollected: [{required: true, message: '未收账款[开票未到账+未开票金额]不能为空', trigger: 'blur'}],
	// expectedReturnTime: [{required: true, message: '预计回款时间不能为空', trigger: 'blur'}],
	// needReturnMoneyYear: [{required: true, message: '当年需回款额不能为空', trigger: 'blur'}],
	// realReturnMoneyYear: [{required: true, message: '当年实际回款额不能为空', trigger: 'blur'}],
	// remainderMoneyYear: [{required: true, message: '当年剩余回款不能为空', trigger: 'blur'}],
	// paymentCollectionYearStaus: [{required: true, message: '当年回款状态不能为空', trigger: 'blur'}],
	// businessRemark: [{required: true, message: '商务备注不能为空', trigger: 'blur'}],
	// bidServiceFee: [{required: true, message: '中标服务费(单位:元)不能为空', trigger: 'blur'}],
	// bidServiceFeeInvoice: [{required: true, message: '中标服务费发票领取情况不能为空', trigger: 'blur'}],
	// remark: [{required: true, message: '备注不能为空', trigger: 'blur'}],
});

// 打开弹窗
const openDialog = (id: string) => {
	visible.value = true;
	form.value.id = '';
	form.value.projectStatus = '';
	getDeptData();
	// 重置表单数据
	nextTick(() => {
		form.value = generateForm();
		dataFormRef.value?.resetFields();
	});

	// 获取projectBasicInfo信息
	if (id) {
		form.value.id = id;
		getprojectBasicInfoData(id);
	}
};

// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		loading.value = true;
		form.value.id ? await putObj(form.value) : await addObj(form.value);
		useMessage().success(form.value.id ? '修改成功' : '添加成功');
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

// 初始化表单数据
const getprojectBasicInfoData = (id: string) => {
	// 获取数据
	loading.value = true;
	getObj(id)
		.then((res: any) => {
			Object.assign(form.value, res.data);
		})
		.finally(() => {
			loading.value = false;
		});
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>
